﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using WeiboWPSdk.Json;
using WeiboWPSdk.Json.Linq;

namespace WeiboWPSdk {
    /// <summary>
    /// 微博工具类
    /// </summary>
    public static  class Utility {
        /// <summary>
        /// 将微博时间转换为DateTime
        /// </summary>
        /// <param name="dateString">微博时间字符串</param>
        /// <returns>DateTime</returns>
        public static DateTime ParseUTCDate(string dateString) {
            System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
            DateTime dt = DateTime.ParseExact(dateString, "ddd MMM dd HH:mm:ss zzz yyyy", provider);
            return dt;
        }
        internal static IEnumerable<string> GetStringListFromJson(string json) {
            var result = JsonConvert.DeserializeObject<IEnumerable<JObject>>(json);
            List<string> list = new List<string>();
            foreach (var loc in result) {
                foreach (var x in loc.Properties()) {
                    list.Add(x.Value.ToString());
                }
            }
            return list;
        }
        internal static Dictionary<string, string> GetDictionaryFromJson(string json) {
            var result = JsonConvert.DeserializeObject<IEnumerable<JObject>>(json);

            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var loc in result) {
                foreach (var x in loc.Properties()) {
                    dict.Add(x.Name, x.Value.ToString());
                }
            }
            return dict;
        }
        /// <summary>
        /// 将字典对象组建成请求字符串
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        internal static string BuildQueryString(Dictionary<string, string> parameters) {
            List<string> pairs = new List<string>();
            foreach (KeyValuePair<string, string> item in parameters) {
                if (string.IsNullOrEmpty(item.Value))
                    continue;

                pairs.Add(string.Format("{0}={1}", Uri.EscapeDataString(item.Key), Uri.EscapeDataString(item.Value)));
            }

            return string.Join("&", pairs.ToArray());
        }
        /// <summary>
        /// 将 WeiboParameter[] 对象组建成请求字符串
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        internal static string BuildQueryString(params WeiboParameter[] parameters) {
            List<string> pairs = new List<string>();
            foreach (var p in parameters) {
                if (p.Value == null) continue;
                if (p.IsBinaryData) continue;
                var value = p.Value.ToString();
                if (!string.IsNullOrEmpty(value))
                    pairs.Add(string.Format("{0}={1}", Uri.EscapeDataString(p.Name), Uri.EscapeDataString(value)));
            }
            return string.Join("&", pairs.ToArray());
        }
        /// <summary>
        /// 创建Post Body
        /// </summary>
        /// <param name="boundary"></param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        internal static byte[] BuildPostData(string boundary, params WeiboParameter[] parameters) {
            List<WeiboParameter> pairs = new List<WeiboParameter>(parameters);
            pairs.Sort(new WeiboParameterComparer());
            MemoryStream buff = new MemoryStream();

            byte[] headerBuff = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}\r\n", boundary));
            byte[] footerBuff = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--", boundary));

            StringBuilder contentBuilder = new StringBuilder();

            foreach (WeiboParameter p in pairs) {
                if (!p.IsBinaryData) {
                    var value = string.Format("{0}", p.Value);
                    if (string.IsNullOrEmpty(value)) {
                        continue;
                    }

                    buff.Write(headerBuff, 0, headerBuff.Length);
                    byte[] dispositonBuff = Encoding.UTF8.GetBytes(string.Format("content-disposition: form-data; name=\"{0}\"\r\n\r\n{1}", p.Name, p.Value.ToString()));
                    buff.Write(dispositonBuff, 0, dispositonBuff.Length);
                }
                else {
                    buff.Write(headerBuff, 0, headerBuff.Length);
                    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: \"image/unknow\"\r\nContent-Transfer-Encoding: binary\r\n\r\n";
                    byte[] fileBuff = System.Text.Encoding.UTF8.GetBytes(string.Format(headerTemplate, p.Name, string.Format("upload{0}", BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0))));
                    buff.Write(fileBuff, 0, fileBuff.Length);
                    byte[] file = (byte[])p.Value;
                    buff.Write(file, 0, file.Length);
                }
            }

            buff.Write(footerBuff, 0, footerBuff.Length);
            buff.Position = 0;

            byte[] contentBuff = new byte[buff.Length];
            buff.Read(contentBuff, 0, contentBuff.Length);
            buff.Close();
            buff.Dispose();
            return contentBuff;
        }
        internal static string GetBoundary() {
            string pattern = "abcdefghijklmnopqrstuvwxyz0123456789";
            StringBuilder boundaryBuilder = new StringBuilder();
            Random rnd = new Random();
            for (int i = 0; i < 10; i++) {
                var index = rnd.Next(pattern.Length);
                boundaryBuilder.Append(pattern[index]);
            }
            return boundaryBuilder.ToString();
        }
    }

    internal enum HttpRequestMethod { 
        Get,
        Post
    }

    /// <summary>
    /// Token验证返回值
    /// </summary>
    public enum TokenResult {
        AuthFailed,
        /// <summary>
        /// 正常
        /// </summary>
        Success,
        /// <summary>
        /// Token已过期
        /// </summary>
        TokenExpired,
        /// <summary>
        /// Token已被占用
        /// </summary>
        TokenUsed,
        /// <summary>
        /// Token已被回收
        /// </summary>
        TokenRevoked,
        /// <summary>
        /// Token被拒绝
        /// </summary>
        TokenRejected,
        /// <summary>
        /// 其他问题
        /// </summary>
        Other
    }

    /// <summary>
    /// 授权认证返回类型
    /// </summary>
    public enum ResponseType {
        /// <summary>
        /// Code
        /// </summary>
        Code,
        /// <summary>
        /// Access Token
        /// </summary>
        Token
    }

    /// <summary>
    /// 回调返回类型
    /// </summary>
    public enum DisplayType {
        /// <summary>
        /// 默认
        /// </summary>
        Default,
        /// <summary>
        /// 移动界面
        /// </summary>
        Mobile,
        /// <summary>
        /// 弹出窗
        /// </summary>
        Popup,
        /// <summary>
        /// Wap12
        /// </summary>
        Wap12,
        /// <summary>
        /// Wap20
        /// </summary>
        Wap20,
        /// <summary>
        /// Javascript
        /// </summary>
        JS,
        /// <summary>
        /// 刷新框架
        /// </summary>
        ApponWeibo
    }

    internal enum GrantType {
        AuthorizationCode,
        Password,
        RefreshToken
    }

    /// <summary>
    /// WeiboParameter实现的IComparer接口
    /// </summary>
    internal class WeiboParameterComparer : IComparer<WeiboParameter> {
        public int Compare(WeiboParameter x, WeiboParameter y) {
            return StringComparer.CurrentCulture.Compare(x.Name, y.Name);
        }
    }
}
